<?php
include_once $_SERVER['DOCUMENT_ROOT']."/controller/connect.php";
include_once $_SERVER['DOCUMENT_ROOT']."/model/Location.php";

/**
 * Created by PhpStorm.
 * User: lwh
 * Date: 2017/7/21
 * Time: 10:28
 */
class LocationDAO{
    const FIELD_ID = "locationId";
    const FIELD_STAGE_ID = "stageId";
    const FIELD_ADDRESS = "address";
    const FIELD_LATITUDE = "latitude";
    const FIELD_LONGITUDE = "longitude";
    const FIELD_TYPE = "type";

    public $conn;

    function __construct()
    {
        $this->conn = new db();
    }

    //插入位置
    public function insert($location){

    }

    //删除位置
    public function delete($locationId){

    }

    //查询位置
    public function query($locationId){
        $sql = "select * from location where ".self::FIELD_ID." = ".$locationId;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if($row){
            $location = $this->loadDataFromResult($row);
            return $location;
        }
        return null;
    }

    //更新位置
    public function update($location){

    }

    //根据stage和type查询相应的location
    public function queryByStageAndType($stageId,$type){
        $sql = "select * from location where ".self::FIELD_STAGE_ID." = ".$stageId." and ".self::FIELD_TYPE." = ".$type;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if($row){
            $location = $this->loadDataFromResult($row);
            return $location;
        }
        return null;
    }

    //从结果集中构建出location对象
    private function loadDataFromResult($row){
        $location = new Location();
        $location->setId($row[self::FIELD_ID]);
        $location->setStageId($row[self::FIELD_STAGE_ID]);
        $location->setAddress($row[self::FIELD_ADDRESS]);
        $location->setLatitude($row[self::FIELD_LATITUDE]);
        $location->setLongitude($row[self::FIELD_LONGITUDE]);
        $location->setType($row[self::FIELD_TYPE]);
        return $location;
    }

}